package com.giteelou.antlr.ps.man;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 测试
 * 支持变量声明，声明初始化，赋值语句。
 * 最后一行输入over();开始解释语句。
 * 最后一行输入exit();则退出测试程序。
 */
public class MyTester {

    public static void main(String[] args) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder scriptBuilder = new StringBuilder();
        while (true) {
            System.out.print("\n>");
            try {
                String line = reader.readLine().trim();
                if (line.equals("exit();")) {
                    System.out.println("bye.");
                    break;
                }
                if (!line.equals("over();")) {
                    scriptBuilder.append(" ").append(line);
                    continue;
                }

                Object val = evaluate(scriptBuilder.toString());
                if (val != null) {
                    System.out.println(val);
                }
                scriptBuilder = new StringBuilder();
            } catch (IOException e) {
                System.out.println(e.getLocalizedMessage());
                break;
            }
        }
    }

    private static Object evaluate(String script) {
        Semantics semantics = MyCompiler.compile(script);
        if (!semantics.errors.isEmpty()) {
            System.err.println(">" + semantics.errors.get(0));
            semantics.errors.clear();
            return null;
        }
        ASTEvaluate eva = new ASTEvaluate(semantics);
        return eva.visit(semantics.ast);
    }

}
